package cn.kgc.liverweb.controller;


import cn.kgc.bean.*;
import cn.kgc.service.LiverOrderService;
import cn.kgc.service.LiverService;
import cn.kgc.service.RoomService;
import cn.kgc.utils.CrowdFundingUtils;
import cn.kgc.utils.OrderNoUtils;
import cn.kgc.utils.ResultEntity;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.lang.System;
import java.util.*;

@Controller
@CrossOrigin
public class LiverController {
    @Reference
    LiverService liverService;
    @Reference
    LiverOrderService liverOrderService;

    /*查询维修反馈*/

    /*查询住户*/
    @RequestMapping("liver/getLiver")
    @ResponseBody
    public ResultEntity getLiver(@RequestParam(required = false,defaultValue = "1") Integer pageNum,
                                 @RequestParam(required = false,defaultValue = "")String loginName){
        PageInfo<Liver> liver = liverService.getLiver(pageNum, 10, loginName);
        return ResultEntity.successWithoutData(liver);

    }
    //登录
    @RequestMapping("/liver/login")
    @ResponseBody
    public ResultEntity login(
            @RequestParam(required = false,defaultValue = "")String loginName,
            @RequestParam(required = false,defaultValue = "")String password,
            Map<String,Object> map,
            Model model
    ){
          Liver login = liverService.login(loginName, password);
          if (login==null){
              /*用户不存在或未激活*/
              map.put("result","null");
          }else{
              if (login.getId()==0){
                  /*密码错误*/
                  map.put("result","error");
              }else{
                  /*登录成功*/
                  map.put("result","success");
                  map.put("user",login);
              }
          }
          return ResultEntity.successWithoutData(map);
    }
    //注册
    @RequestMapping("/liver/regist")
    @ResponseBody
    public ResultEntity regist(
            @RequestParam(required = false,defaultValue = "") String registName,
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false,defaultValue = "") String password,
            @RequestParam(required = false,defaultValue = "") String code,
            Map<String,Object> map
    ){
        try {
            String phone="";
            String email="";
            if (type==0){
                if (registName.contains("@")){
                    map.put("result","faild");
                    return ResultEntity.successWithoutData(map);
                }
                phone=registName;
                System.out.println(registName.contains("@"));

            }else{
                if (!registName.contains("@")){
                    map.put("result","faild");
                    return ResultEntity.successWithoutData(map);
                }
                email=registName;
                System.out.println(registName.contains("@"));
            }
            int regist = liverService.regist(phone, email, password, code);
            if (regist>0){
               if (regist==1){
                   map.put("result","notnull");
               }else{
                   map.put("result","success");
               }
            }else{
                map.put("result","faild");
            }
            return ResultEntity.successWithoutData(map);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return ResultEntity.failed(e.getMessage());
        }
    }

    //实名认证
    @RequestMapping("/liver/bind")
    @ResponseBody
    public ResultEntity update(
            Integer id,String name,String idcard,
            Map<String,Object> map
    ){
        Liver liver = liverService.getLiverById(id);
        liver.setName(name);
        liver.setIdcard(idcard);
        int update = liverService.update(liver);
        if (update>0){
            map.put("result","success");
        }else{
            map.put("result","faild");
        }
        return ResultEntity.successWithoutData(map);
    }
    /*绑定公寓*/
    @Reference
    RoomService roomService;
    @RequestMapping("/liver/bindHouse")
    @ResponseBody
    public ResultEntity bindHouse(Integer id,Integer houseid){
        Map<String,Object> map=new HashMap<>();
        Liver liver=liverService.getLiverById(id);
        if (houseid!=0){
            House house = liverService.getHouseById(houseid);
            if (house==null){
                map.put("result","nohouse");
                return ResultEntity.successWithoutData(map);
            }
        }
        if (liver.getHouseid()!=null&&liver.getHouseid()!=0){
            House house = liverService.getHouseById(liver.getHouseid());
            Manage manage = liverService.selectZmanageByHouseId(liver.getHouseid());
            if (liver.getYanjin()!=null&&liver.getYanjin()>0){
                double zmoney=manage.getMoney();
                if (zmoney<liver.getYanjin()){
                    //总管理没有足够的余额完成押金退回
                    map.put("msg","公寓余额不足以退还押金");
                    map.put("result","faild");
                    return ResultEntity.successWithoutData(map);
                }
                manage.setMoney(zmoney-liver.getYanjin());
                liver.setMoney(liver.getMoney()+liver.getYanjin());
                liver.setYanjin(0.0);
                liverService.updateZmanagerMoney(manage);
            }
        }
        liver.setEndtime(null);
        liver.setHouseid(houseid);
        Integer roomid = liver.getRoomid();
        if (roomid!=null&&roomid!=0){
            Room room = roomService.selectRoomById(roomid);
            room.setRoomnow(room.getRoomnow()-1);
            roomService.updateRoom(room);
            liver.setRoomid(0);
        }
        liver.setStarttime(new Date());
        liver.setEndtime(new Date());
        int update = liverService.update(liver);
        if (update>0){
            map.put("result","success");
        }else{
            map.put("result","faild");
        }
        return ResultEntity.successWithoutData(map);
    }



    /*根据id查询住户信息*/
    @RequestMapping("/liver/selectLiverById")
    @ResponseBody

    public ResultEntity selectLiverById(
            @RequestParam(required = false)Integer id,
            Map<String,Object> map
    ){
        Liver liverById = liverService.getLiverById(id);
        if (liverById==null){
            map.put("result","null");
        }else{
            map.put("result",liverById);
        }
        return ResultEntity.successWithoutData(map);
    }
    /*根据id查询公寓信息*/
    @RequestMapping("/liver/selectHouseById")
    @ResponseBody
    public ResultEntity  selectHouseById(
            @RequestParam(required = false)Integer id,
            Map<String,Object> map
    ){
        if (id==0){
            map.put("result","您已经被上一个公寓移除");
            return ResultEntity.successWithoutData(map);
        }else{
            House houseById = liverService.getHouseById(id);
            if (houseById==null){
                map.put("result","null");
            }else{
                map.put("result",houseById);
            }
            return ResultEntity.successWithoutData(map);
        }
    }
    /*发送验证码*/
    @RequestMapping("/liver/sendCode")
    @ResponseBody
    public ResultEntity sendCode(@RequestParam(defaultValue = "",required = false)String registName,
                                       @RequestParam(required = false) Integer type,
                                       Map<String,Object> map){

        Random random=new Random();
        String code= String.valueOf((int)((Math.random()*9+1)*100000));
        Map<String, Object> mapResult = liverService.addLiverCode(code, registName, type);
        String result=String.valueOf(mapResult.get("result"));
        if (result.equals("success")){
            map.put("result","success");
        }else{
            map.put("result","error");
        }
        return ResultEntity.successWithoutData(map);
    }
    /*重置密码*/
    @RequestMapping("/liver/to/setpwd")
    @ResponseBody
    public String setpwd(String code,String loginName){
        List<Liver> livers = liverService.selectLiverList();
        if (livers.size()>0){
            Liver dataliver=null;
            if (loginName.contains("@")){
                for (Liver liver : livers) {
                    if (liver.getEmail()!=null&&!liver.getEmail().equals("")){
                        if (liver.getEmail().equals(loginName)){
                            dataliver=liver;
                            if (liver.getCode().equals(CrowdFundingUtils.md5(code))){
                                liver.setCode("0000");
                                liverService.update(liver);
                                return "<div style='text-align='center''><h1 style='color:blue'>MyHouse住户密码重置</h1><form  method='post' action='/liver/setpwd'><input type='text' hidden='hidden' name='code' value='"+liver.getCode()+"'>帐号:<input name='loginName' type='text' readonly='readonly' value='"+loginName+"'><br>新密码:<input type='text' placeholder='请输入新密码' name='password'><br><button type='submit'>确认修改</button></form><span style='color:red'>提示:为安全起见,本页面发送一次验证只可打开一次,关闭或刷新后需要重新操作才可进入!给您带来的不便敬请谅解!</span></div>";
                            }
                        }
                    }
                }
                if (dataliver==null){
                    return "无效的请求{result:Don't hava that liver for this loginName-email:"+loginName+"}";
                }
            }else{
                for (Liver liver : livers) {
                    if (liver.getPhone()!=null&&!liver.getPhone().equals("")){
                        if (liver.getPhone().equals(loginName)){
                            dataliver=liver;
                            if (liver.getCode().equals(CrowdFundingUtils.md5(code))){
                                liver.setCode("0000");
                                liverService.update(liver);
                                return "<head> <link rel=\"stylesheet\" type=\"text/css\" href=\"/webjars/bootstrap/3.3.7/css/bootstrap.css\"/></head><html><div class='container'><div style='text-align='center''><h1 style='color:blue'>MyHouse住户密码重置</h1><form  method='post' action='/liver/setpwd'><input type='text' hidden='hidden' name='code' value='"+liver.getCode()+"'>帐号:<input name='loginName' type='text' readonly='readonly' value='"+loginName+"'><br>新密码:<input type='text' placeholder='请输入新密码' name='password'><br><button type='submit'>确认修改</button></form><span style='color:red'>提示:为安全起见,本页面发送一次验证只可打开一次,关闭或刷新后需要重新操作才可进入!给您带来的不便敬请谅解!</span></div></div></html>";
                            }
                        }
                    }
                }
                if (dataliver==null){
                    return "无效的请求{result:Don't hava that liver for this loginName-phone:"+loginName+"}";
                }
            }
        }else{
            return "非法请求";
        }
        return "无效请求或页面已经失效";


    }
    @RequestMapping("/liver/setpwd")
    @ResponseBody
    public String setPwd(String loginName,String password,String code) {
        if (code.equals("0000")) {
            if (password == null || password.equals("")) {
                return "无效请求!";
            } else {
                List<Liver> livers = liverService.selectLiverList();
                if (loginName.contains("@")) {
                    for (Liver liver : livers) {
                        if (liver.getEmail().equals(loginName)) {
                            if (!liver.getCode().equals(CrowdFundingUtils.md5("set"))) {

                                liver.setPassword(CrowdFundingUtils.md5(password));
                                liver.setCode(CrowdFundingUtils.md5("set"));
                                liverService.update(liver);
                                return "<h1>修改成功!<a href='http://localhost:8080/login.html'>点击返回登录</a></h1>";
                            } else {
                                return "您已经完成了密码修改!如若需要重新操作,请重新获取验证信息<a href='http://localhost:8080/login.html'>点我去登录</a>";
                            }
                        }
                    }
                    }else{
                        for (Liver liver : livers) {
                            if (liver.getPhone().equals(loginName)) {
                                if (!liver.getCode().equals(CrowdFundingUtils.md5("set"))) {
                                    liver.setPassword(CrowdFundingUtils.md5(password));
                                    liver.setCode(CrowdFundingUtils.md5("set"));
                                    liverService.update(liver);
                                    return "<h1>修改成功!<a href='http://localhost:8080/login.html'>点击返回登录</a></h1>";
                                } else {
                                    return "您已经完成了密码修改!如若需要重新操作,请重新获取验证信息<a href='http://localhost:8080/login.html'>点我去登录</a>";
                                }
                            }
                        }
                    }
                }
            }else{
                return "非法请求";
            }
        return "无效请求或页面已经失效!";
    }

    /*用户充值*/
    @RequestMapping("/liver/pay")
    @ResponseBody
    public ResultEntity<Map<String, Object>> liverPay(Map<String,Object> map, Integer uid, String money, HttpServletResponse response) throws Exception {
        Liver liver = liverService.getLiverById(uid);
        House house = liverService.getHouseById(liver.getHouseid());
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        map.put("price",money);
        map.put("gremark","MyHouse用户充值支付-充值对象:"+liver.getName());
        map.put("contact",liver.getName());
        map.put("houseId",liver.getHouseid());
        map.put("uid",uid);
        map.put("houseName",house.getHousename());
        return ResultEntity.successWithoutData(map);
    }
    /*用户房租缴费或押金操作 properties 0为充值 1为住宿缴费 2为其它缴费 3为押金缴纳 4为押金退回  day是由前端传过来的续租多少天 remark是订单备注 total是其它缴费时的缴费金额 如果是住宿缴费则只需要传入day即可*/
    @RequestMapping("/liver/pay2")
    @ResponseBody
    public ResultEntity pay2(Map<String,Object> map,Integer id,Integer properties,@RequestParam(required = false) Integer day,String remark,@RequestParam(required = false,defaultValue = "0")String total){
        if (properties==0){
            map.put("result","无效操作");
            return  ResultEntity.successWithoutData(map);
        }else{
            /*根据id获取住户信息*/
            Liver liver = liverService.getLiverById(id);
            if (liver==null){
                map.put("result","无效操作,用户不存在");
                return ResultEntity.successWithoutData(map);
            }
            /*根据住户的房间编号查询房间信息*/
            Room room=liverService.selectRoomById(liver.getRoomid());
            if (room==null){
                map.put("result","无效操作,用户未绑定房间");
                return ResultEntity.successWithoutData(map);
            }
            /*根据住户的公寓id查询公寓信息*/
            House house = liverService.getHouseById(liver.getHouseid());
            if (house==null){
                map.put("result","无效操作,用户未绑定公寓");
                return ResultEntity.successWithoutData(map);
            }
            /*生成订单*/
            double money=0.0;
           if (day!=null){
               Double price=room.getDayprice();
               money=day*price;
           }else{
               money=Double.parseDouble(total);
           }
            Liverorder liverorder=new Liverorder();
            liverorder.setState(0);
            liverorder.setProperties(properties);
            liverorder.setUname(liver.getName());
            liverorder.setOrderno(OrderNoUtils.getOrderNo());
            liverorder.setHouseid(house.getId());
            liverorder.setHousename(house.getHousename());
            liverorder.setUid(id);
            liverorder.setMoney(money);
            liverorder.setDate(new Date());
            liverorder.setRemark(remark);
            liverService.addLiverOrder(liverorder);
            /*修改住户余额*/
            if (properties!=4){
                Double liverMoney=liver.getMoney();
                if (liverMoney<money){
                    map.put("result","余额不足");
                    return ResultEntity.successWithoutData(map);
                }
                liver.setMoney(liverMoney-money);
                if (properties==3){
                    liver.setYanjin(money);
                }
                if (properties==1){
                    if (liver.getEndtime()==null){
                        liver.setEndtime(new Date());
                    }
                    Calendar calendar=Calendar.getInstance();
                    calendar.setTime(liver.getEndtime());
                    calendar.add(Calendar.DATE,day);
                    liver.setEndtime(calendar.getTime());
                }
            }else{

                liver.setMoney(liver.getMoney()+liver.getYanjin());
                liver.setYanjin(0.0);
            }

            /*根据公寓id查询公寓总管理信息*/
            Manage manage = liverService.selectZmanageByHouseId(house.getId());
            /*修改公寓总管理余额*/
            if (properties!=4){
                manage.setMoney(manage.getMoney()+money);
            }else{
                double zmoney=manage.getMoney();
                if (zmoney<money){
                    //总管理没有足够的余额完成押金退回
                    map.put("result","公寓余额不足以退还押金");
                    return ResultEntity.successWithoutData(map);
                }
                manage.setMoney(zmoney-money);
            }
            liverService.update(liver);
            liverService.updateZmanagerMoney(manage);
            System.out.println(new Date("1988/06/06"));
            PageInfo<Liverorder> pageInfo = liverOrderService.selectLiverOrders(1, 1, 0, new Date("1988/06/06"), new Date("1988/06/06"), liverorder.getOrderno(), "");
            Liverorder liverorder1 = pageInfo.getList().get(0);
            liverorder1.setState(1);
            liverOrderService.update(liverorder1);
            map.put("result","success");
            map.put("money",money);
            return ResultEntity.successWithoutData(map);


        }
    }
    /*用户缴费记录查询*/
    @RequestMapping("/liver/selectPay")
    @ResponseBody
    public ResultEntity selectPay(@RequestParam(required = false,defaultValue = "1") Integer pageNum,Integer id,Date startDate,Date endDate){
        PageInfo<Liverorder> pageInfo = liverService.selectOrders(pageNum,7,id, startDate, endDate);
        return ResultEntity.successWithoutData(pageInfo);
    }
    /*用户维修反馈*/

    @RequestMapping("/liver/wxfk")
    @ResponseBody
    public ResultEntity wxfk(Integer id,String content){
        Wxfk wxfk=new Wxfk();
        wxfk.setUid(id);
        wxfk.setFkcontent(content);
        wxfk.setState(0);
        wxfk.setStartdate(new Date());
        Liver liver = liverService.getLiverById(id);
        wxfk.setHouseid(liver.getHouseid());
        int i = liverService.addWxfk(wxfk);
        if (i>0){
            return ResultEntity.successWithoutData("success");
        }else{
            return ResultEntity.successWithoutData("faild");
        }

    }
    /*根据反馈id查询反馈信息*/
    @RequestMapping("/liver/getwxfk")
    @ResponseBody
    public ResultEntity getwxfk(Integer id){
        Wxfk wxfkById = liverService.getWxfkById(id);
        return ResultEntity.successWithoutData(wxfkById);
    }
    /*根据id查询房间信息*/
    @RequestMapping("/liver/getRoomInfo")
    @ResponseBody
    public ResultEntity getRoomInfo(Integer roomid){
        Room room = liverService.selectRoomById(roomid);
        if (room!=null){
            return ResultEntity.successWithoutData(room);
        }else{
            return ResultEntity.successWithoutData("没有查询到id为"+roomid+"的room信息,请检查");
        }
    }
    /*修改密码*/
    @RequestMapping("/liver/updatePassword")
    @ResponseBody
    public ResultEntity updatePassword(Integer id,String oldPassword,String newPassword){
        Map<String,Object> map=new HashMap<>();
        Liver liver = liverService.getLiverById(id);
        String md5Old= CrowdFundingUtils.md5(oldPassword);
        if (md5Old.equals(liver.getPassword())){
            liver.setPassword(CrowdFundingUtils.md5(newPassword));
            int update = liverService.update(liver);
            if (update>0){
                map.put("result","success");
                map.put("newpassword",newPassword);
                return ResultEntity.successWithoutData(map);
            }else{
                map.put("result","修改失败,服务器错误");
                return ResultEntity.successWithoutData(map);
            }
        }else{
            map.put("result","false");
            return ResultEntity.successWithoutData(map);
        }


    }
    /*住户提现*/
    @RequestMapping("/liver/getMoney")
    @ResponseBody
    //money:提现金额 bankNum银行卡号 id用户id
    public ResultEntity getMoney(Integer id,String money,String bankNum){
        Map<String,Object> map=new HashMap<>();
        Liver liver = liverService.getLiverById(id);
        double liverMoney=liver.getMoney();
        double imoney=Double.parseDouble(money);
        double ratemoney=0;
        if (imoney>=100000){
            ratemoney=100;
        }else{
            if (imoney<=100){
                ratemoney=0.1;
            }else{
                ratemoney=imoney*0.001;
            }
        }
        if (imoney+ratemoney>liverMoney){
            map.put("result","nomoney");
            return ResultEntity.successWithoutData(map);
        }else{
            ratemoney=Double.parseDouble(new Formatter().format("%.2f", ratemoney).toString());
            liver.setMoney(liverMoney-ratemoney-imoney);
            int update = liverService.update(liver);
            if (update>0){
                Liverorder liverorder=new Liverorder();
                liverorder.setState(1);
                liverorder.setDate(new Date());
                liverorder.setHouseid(liver.getHouseid());
                House house = liverService.getHouseById(liver.getHouseid());
                liverorder.setHousename(house.getHousename());
                liverorder.setMoney(imoney+ratemoney);
                liverorder.setOrderno(OrderNoUtils.getOrderNo());
                liverorder.setProperties(5);
                liverorder.setUid(id);
                liverorder.setUname(liver.getName());
                int i = liverService.addLiverOrder(liverorder);
                if (i>0){
                    map.put("result","success");
                    /*手续费返回值*/
                    map.put("ratemoney",ratemoney);
                }else{
                    map.put("result","订单创建失败");
                }

            }else{
                map.put("result","服务器数据错误");
            }
            return ResultEntity.successWithoutData(map);
        }


    }
    //------------!!!!--------------------------------===------------------
    /*上传房间图片*/
    @RequestMapping("liver/upRoomImg")
    public ResultEntity upRoomImg(){

        return ResultEntity.successWithoutData("success");
    }
    /*查询优质房源*/
    @RequestMapping("liver/getBetterRoom")
    //areaKeyword:地区关键字  houseid,公寓编号,可空
    public ResultEntity getBetterRoom(String areaKeyword,Integer houseid){

        return ResultEntity.successWithoutData("success");
    }
    /*导出缴费记录*/
    @RequestMapping("liver/exportLiverOrders")
    public ResultEntity  exportLiverOrders(){
        return ResultEntity.successWithoutData("success");
    }

    /*导出维修反馈记录*/
    @RequestMapping("liver/exportLiverWxfks")
    public ResultEntity  exportLiverWxfks(){
        return ResultEntity.successWithoutData("success");
    }





   @ExceptionHandler
    public ResultEntity exception(){

        System.err.println(new Date()+"时在LiverController发现错误!");
        return ResultEntity.failed("系统错误","MyHouse提示:抱歉,您当前的操作无法正常完成,可能是系统出现了故障,请稍等五分钟后重试,如若长时间无法操作,您可以发送邮件至lgp1022@foxmail.com与我们反馈,给您带来的不便我们深表歉意.祝您工作顺利,生活愉快.");
    }







}
